package com.example.myapplication;

import android.util.Log;

import androidx.lifecycle.MutableLiveData;

import com.google.gson.Gson;

import org.json.JSONObject;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Test <T>{
    public MutableLiveData<T> liveData;
    public void get(String url,Class<T> tClass){
        liveData = new MutableLiveData<T>();
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient().newBuilder()
                        .build();
                Request request = new Request.Builder()
                        .url(url)
                        .method("GET", null)
                        .build();
                try {
                    Response response = client.newCall(request).execute();
                    String string = response.body().string();
                    Log.i("TAG", "run: "+string);
                    T t = new Gson().fromJson(string, tClass);
                    liveData.postValue(t);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    public void post(String url, Class<T> tClass, JSONObject jsonObject){
        liveData = new MutableLiveData<T>();
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient().newBuilder()
                        .build();
                MediaType mediaType = MediaType.parse("application/json");
                RequestBody body = RequestBody.create(mediaType, jsonObject.toString());

                Request request = new Request.Builder()
                        .url(url)
                        .method("POST", body)
                        .addHeader("Content-Type", "application/json")
                        .build();
                try {
                    Response response = client.newCall(request).execute();
                    String strings = response.body().string();
                    Log.i("TAG", "run: "+strings);
                    T t = new Gson().fromJson(strings, tClass);
                    liveData.postValue(t);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


}
